package com.yvan.codeslave.ui;

import com.intellij.openapi.fileChooser.FileChooser;
import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory;
import com.intellij.openapi.module.ModuleManager;
import com.intellij.openapi.options.Configurable;
import com.intellij.openapi.options.ConfigurationException;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.VirtualFileManager;
import com.yvan.codeslave.PluginUtils;
import lombok.val;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;

public class MainSetting implements Configurable, Configurable.Composite {
    private JTextField authorTextField;
    private JTextField basePathTextField;
    private JButton chooseButton;
    private JPanel mainPanel;


    public MainSetting() {

        init();

        chooseButton.addActionListener(e -> {

            val project = PluginUtils.getProject();

            VirtualFile path = project.getBaseDir();
            val modules = ModuleManager.getInstance(project).getModules();
            if (modules.length > 0) {
                path = VirtualFileManager.getInstance().findFileByUrl("file://" + modules[0].getModuleFilePath());
            }

            VirtualFile virtualFile = FileChooser.chooseFile(FileChooserDescriptorFactory.createSingleFolderDescriptor(), project, path);
            if (virtualFile != null) {
                basePathTextField.setText(virtualFile.getPath());
            }
        });
    }

    @Nls
    @Override
    public String getDisplayName() {
        return "Code Slave";
    }

    @NotNull
    @Override
    public Configurable[] getConfigurables() {
        return new Configurable[0];
    }

    @Nullable
    @Override
    public JComponent createComponent() {
        return mainPanel;
    }

    @Override
    public boolean isModified() {
        val state = PluginUtils.getState();
        if (state == null) {
            return true;
        }

        return !authorTextField.getText().equals(state.author) ||
                !basePathTextField.getText().equals(state.basePath);
    }

    @Override
    public void apply() throws ConfigurationException {
        //保存数据
        val state = new PluginUtils.State();
        state.author = authorTextField.getText();
        state.basePath = basePathTextField.getText();
        PluginUtils.save(state);
    }

    /**
     * 初始化方法
     */
    private void init() {
        //初始化数据
        val state = PluginUtils.getState();
        if (state == null) {
            authorTextField.setText("");
            basePathTextField.setText("");
        } else {
            authorTextField.setText(state.author);
            basePathTextField.setText(state.basePath);
        }
    }

    /**
     * 重置
     */
    @Override
    public void reset() {
        init();
    }
}
